package com.atguigu.yygh.order.service.impl;

import com.atguigu.yygh.enums.PaymentStatusEnum;
import com.atguigu.yygh.enums.PaymentTypeEnum;
import com.atguigu.yygh.model.order.OrderInfo;
import com.atguigu.yygh.model.order.PaymentInfo;
import com.atguigu.yygh.order.mapper.PaymentInfoMapper;
import com.atguigu.yygh.order.service.OrderInfoService;
import com.atguigu.yygh.order.service.PaymentInfoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

/**
 * @Author:hx
 * @DateTime:2022/11/19 13:36
 * @Description:
 */
@Service
public class PaymentInfoServiceImpl extends ServiceImpl<PaymentInfoMapper,PaymentInfo> implements PaymentInfoService {

    @Autowired
    private OrderInfoService orderInfoService;

    @Override
    public void savePaymentInfo(Long orderId) {

        OrderInfo orderInfo = orderInfoService.getById(orderId);

        //判断预支付信息是否存在
        QueryWrapper<PaymentInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id",orderId);
        PaymentInfo paymentInfo1 = baseMapper.selectOne(queryWrapper);

        PaymentInfo paymentInfo = new PaymentInfo();

        if (paymentInfo1 == null){
            paymentInfo.setOutTradeNo(orderInfo.getOutTradeNo());
            paymentInfo.setOrderId(orderInfo.getId());
            paymentInfo.setPaymentType(PaymentTypeEnum.WEIXIN.getStatus());
            paymentInfo.setTotalAmount(orderInfo.getAmount());
            paymentInfo.setPaymentStatus(PaymentStatusEnum.UNPAID.getStatus());
            paymentInfo.setSubject("尚医通预约挂号费用");
            baseMapper.insert(paymentInfo);
        }
    }

    @Override
    public void updatePaymentInfo(Map<String, String> xmlToMap, Long orderId) {
        UpdateWrapper<PaymentInfo> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("order_id",orderId);
        PaymentInfo paymentInfo = new PaymentInfo();
        paymentInfo.setTradeNo(xmlToMap.get("transaction_id"));
        paymentInfo.setCallbackTime(new Date());
        paymentInfo.setCallbackContent(xmlToMap.toString());
        paymentInfo.setPaymentStatus(PaymentStatusEnum.PAID.getStatus());
        baseMapper.update(paymentInfo,updateWrapper);
    }

    @Override
    public void updatePaymentStatus(Long orderId) {
        UpdateWrapper<PaymentInfo> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("order_id",orderId);
        PaymentInfo paymentInfo = new PaymentInfo();
        paymentInfo.setPaymentStatus(PaymentStatusEnum.REFUND.getStatus());
        baseMapper.update(paymentInfo,updateWrapper);
    }
}
